package com.celesea.oauth2.user.service;

import com.celesea.framework.authority.AuthorityPoint;
import com.celesea.framework.authority.AuthorityPrincipal;
import com.celesea.framework.authority.AuthorityRole;
import com.celesea.framework.authority.Tenant;
import com.celesea.oauth2.user.dao.UserDao;
import com.celesea.oauth2.user.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author JackYuan
 * @create 2017-11-08 21:12
 */
@Service
public class UserServiceImpl implements UserService {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        AuthorityPrincipal principal = new AuthorityPrincipal();
        principal.setUpdateTime(System.currentTimeMillis());
        User user = selectByUserName(username);
        principal.setUsername(user.getAccount());
        principal.setPassword(user.getPassword());
        principal.setRoles(selectRoles(user));
        principal.setPoints(selectPoint(user));
        principal.setTenant(selectTenant(user));
        // TODO
        return principal;
    }


    private Tenant selectTenant(User user) {
        Tenant tenant = new Tenant();
        tenant.setId(user.getTenantId());
        return tenant;
    }


    private Set<AuthorityPoint> selectPoint(User user) {
        String[] points = new String[]{"ROLE_ADMIN", "ROLE_USER"};
        return Arrays.stream(points).map(point -> new AuthorityPoint(point)).collect(Collectors.toSet());
    }

    private Set<AuthorityRole> selectRoles(User user) {
        String[] roleCodes = new String[]{"Admin", "Boos"};
        return Arrays.stream(roleCodes).map(code -> new AuthorityRole(null, code)).collect(Collectors.toSet());
    }

    private User selectByUserName(String username) {
        Example example = new Example(User.class);
        Example.Criteria criteria1 = example.createCriteria();
        criteria1.andEqualTo("account", username);
        List<User> users = userDao.selectByExample(example);
        if (CollectionUtils.isEmpty(users)) {
            logger.error("用户名：{}不存在", username);
            throw new UsernameNotFoundException(String.format("用户名：%s不存在。", username));
        }
        return users.get(0);
    }
}
